package com.eduplatform.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.eduplatform.service.BlacklistTokenService;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

@Component
public class JwtUtils {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    // 存储有效的JWT ID，用于验证token是否仍然有效
    private final Map<String, Date> validJwtIds = new ConcurrentHashMap<>();

    @Autowired(required = false)
    private BlacklistTokenService blacklistTokenService;

    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        String jwtId = UUID.randomUUID().toString();
        claims.put("jti", jwtId);

        // 存储JWT ID和过期时间
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        validJwtIds.put(jwtId, expirationDate);

        return createToken(claims, username, expirationDate);
    }

    private String createToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    private String createToken(Map<String, Object> claims, String subject, Date expirationDate) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Boolean validateToken(String token, String username) {
        // 检查token格式
        if (token == null || token.isEmpty() || !token.contains(".") || token.split("\\.").length != 3) {
            return false;
        }

        // 检查token是否在黑名单中
        if (blacklistTokenService != null && blacklistTokenService.isInBlacklist(token)) {
            return false;
        }

        try {
            Claims claims = extractAllClaims(token);
            if (claims == null) {
                return false;
            }

            String jwtId = claims.get("jti", String.class);

            // 检查JWT ID是否存在且未过期
            if (jwtId != null) {
                Date storedExpiration = validJwtIds.get(jwtId);
                if (storedExpiration == null) {
                    // JWT ID不存在，说明token已被注销
                    return false;
                }

                // 清理过期的JWT ID
                if (storedExpiration.before(new Date())) {
                    validJwtIds.remove(jwtId);
                    return false;
                }
            }

            final String extractedUsername = extractUsername(token);
            return (extractedUsername != null && extractedUsername.equals(username) && !isTokenExpired(token));
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 使指定的token失效
     * 
     * @param token JWT token
     * @return 是否成功使token失效
     */
    public boolean invalidateToken(String token) {
        try {
            // 检查token格式
            if (token == null || token.isEmpty() || !token.contains(".") || token.split("\\.").length != 3) {
                return false;
            }

            Claims claims = extractAllClaims(token);
            if (claims == null) {
                return false;
            }

            String jwtId = claims.get("jti", String.class);

            if (jwtId != null) {
                // 从有效JWT ID集合中移除
                validJwtIds.remove(jwtId);
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 清理过期的JWT ID
     */
    public void cleanExpiredJwtIds() {
        Date now = new Date();
        validJwtIds.entrySet().removeIf(entry -> entry.getValue().before(now));
    }

    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claims != null ? claimsResolver.apply(claims) : null;
    }

    private Claims extractAllClaims(String token) {
        try {
            // 检查token格式
            if (token == null || token.isEmpty() || !token.contains(".") || token.split("\\.").length != 3) {
                return null;
            }
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            // 捕获所有可能的异常，包括MalformedJwtException
            return null;
        }
    }

    private Boolean isTokenExpired(String token) {
        try {
            Date expiration = extractExpiration(token);
            return expiration != null && expiration.before(new Date());
        } catch (Exception e) {
            return true; // 如果无法解析过期时间，则认为token已过期
        }
    }
}